package com.share.all.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.share.all.mapper.CityMapper;
import com.share.all.model.City;
import com.share.all.service.AbsractCityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 * 事务注解@Transactional 与缓存注解@CacheEvict等一起使用时注意 https://cloud.tencent.com/developer/article/1551858
 * @author caifan
 * @created 2021/11/13
 * @description:
 */
@CacheConfig(cacheNames = {"city"}, cacheManager = "cacheManager")
@Service
public class CityServiceImpl extends AbsractCityService {

    private final Logger logger = LoggerFactory.getLogger(CityServiceImpl.class);

    public CityServiceImpl(CityMapper cityMapper, RedisTemplate redisTemplate) {
        this.cityMapper = cityMapper;
        this.redisTemplate = redisTemplate;
    }

    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveCity(City city) {
//        ListOperations listOperations = redisTemplate.opsForList();
//        listOperations.leftPush("city", city);
//        save(city);
        cityMapper.insert(city);
    }

    @Cacheable(unless = "#result.size() == 0", keyGenerator = "customKeyGenerator")
    public List<City> allCity() {
        logger.info("city from db");
        return cityMapper.selectList(null);
    }

    @Override
    @Cacheable(key = "#id")
    public City getById(Long id) {
        logger.info("city from db id:{}", id);
        return cityMapper.selectOne(Wrappers.<City>lambdaQuery().eq(City::getId, id));
    }
}
